
import React, { useState, useEffect, useMemo } from 'react'
import Suggest from '../../component/suggest'
import API from '../api/shopCar'
import './index.scss'
import { store } from '../../store'
import { Checkbox, Toast, Space, Button } from 'antd-mobile'
import { MailFill } from 'antd-mobile-icons'
import { IShopCar } from '../../interface'
import { NavLink, useNavigate } from 'react-router-dom'
import { useDispatch,useSelector } from 'react-redux'



export default function ShopCar() {
  const [sum, setSum] = useState<number>(0)
  const [sCar, setSCar] = useState<IShopCar[]>([])
  const [shopCar, setShopCar] = useState<IShopCar[]>([])
  const {tabReducer} = useSelector((state:any)=> state)

  const { token, _id } = store.getState().userReducer.user
  const [changeCheck, setChangeCheck] = useState(false)
  const [value, setValue] = useState<any>(['面包'])
  const [items, setItems] = useState([])
  const isLogin = useMemo(() => token, [token])
  const navigate = useNavigate()
  //总价
  let total = useMemo(() => shopCar.filter((item: IShopCar) => item.onCar).reduce((sum: number, next: IShopCar) => sum + next.price * next.count, 0), [shopCar])
  console.log(total,'666')
  const getShopCar = async () => {
    if (isLogin) {
      let res = await API["getShopCar"]({ _id, token })
      console.log(res, '购物车')
      setShopCar(res.data.data)
      setValue(res.data.data.map((item: IShopCar) => item.goods_name))
      setItems(res.data.data.map((item: any) => item.goods_name))

      setSCar(res.data.data.map((item: any) => {
        item.onCar = true
        return item
      }))
    }
  }

  const countAdd = async (item: IShopCar) => {
    let res = await API['countAdd']({ user_id: item.user_id, token, goods_name: item.goods_name })
    console.log(res, '加数量')
    getShopCar()
  }

  const countDel = async (item: IShopCar) => {
    let res = await API['countDel']({ ...item, token })
    console.log(res, '减数量')
    getShopCar()
  }

  const shopCarDel = async (id: any) => {
    let res = await API['shopCarDel']({ id, token })
    console.log(res, '删除商品')
    Toast.show({
      content: '删除成功',
      position: 'top'
    })
    getShopCar()
  }



  const checkbox = (val: boolean, item: IShopCar) => {
    setShopCar(shopCar.filter((ele: any) => {
      if (ele._id == item._id) {
        ele.onCar = val
        return ele
      } else {
        return ele
      }
    }))
    console.log(sCar, 'sCar')
    setChangeCheck(val)
  }

  useEffect(() => {
    getShopCar()
  }, [])
  return (
    <>
      {
        !isLogin && <div className='noLogin'>还没有登录<NavLink to={'/login'}>请先登录</NavLink>再查看</div>
      }
      {
        isLogin && <div className='shoper'>
          <div className='total'>
            <div className='left'>
              <Checkbox
                checked={value.length === items.length}
                onChange={checked => {
                  console.log(checked, '全部')
                  
                  setShopCar(shopCar.map((item: any) => {
                    item.onCar = checked
                    return item
                  }))
                  console.log(shopCar)
                  if (checked) {
                    setValue(items)
                    
                  } else {
                    setValue([])
                  }
                }}
                style={{
                  '--icon-size': '18px',
                  '--font-size': '14px',
                  '--gap': '6px',
                  'color': '#754428'
                }}
              >
                全选
              </Checkbox>
            </div>

            <div className='right'>
              <span>合计：<b>&yen;{total}</b></span>
              <NavLink to={'/total'} state={{items:sCar,total}}><Button>结算</Button></NavLink>
              {/* <Button onClick={() => navigate('/total')}>结算</Button> */}
            </div>
          </div>
          {
            shopCar.length ? shopCar.map((item: any) => <div className='shop' key={item._id}>
              <div>
                <Checkbox.Group
                  value={value}
                  onChange={v => {
                    setValue(v as string[])
                  }}
                >
                  <Checkbox onChange={(e) => checkbox(e, item)} value={item.goods_name} key={item._id}
                    style={{
                      '--icon-size': '18px',
                      '--font-size': '14px',
                      '--gap': '6px',
                      'color': '#754428'
                    }}
                  >
                  </Checkbox>
                </Checkbox.Group>
                {/* <NavLink to={'/topic/' + item._id}><img src={item.img} alt="" /></NavLink> */}
                <img src={item.img} alt="" />
              </div>
              <ul>

                <div>
                  <span className='span' onClick={() => shopCarDel(item._id)}>删除</span>
                  <p className='p1'>{item.goods_name}</p>
                  <p className='p2'>{item.specs}</p>
                  <div className='liDiv'>
                    <p> &yen;{item.price}</p>
                    <p>
                      <span onClick={() => countDel(item)}>-</span>
                      <i>{item.count}</i>
                      <span onClick={() => countAdd(item)}>+</span>
                    </p>
                  </div>
                </div>
                <li>
                  <img src="https://gd2.alicdn.com/imgextra/i4/166760602/O1CN01EYGcUR1GJkyYmuzIy_!!166760602.jpg_400x400.jpg" alt="" />
                  含{item.cutlery[0]}套餐具（蜡烛生日帽菜单独订购）
                </li>
                <li>
                  <span>生日牌</span>
                  生日快乐
                </li>
              </ul>
            </div>) : <div className='noShopCar'><div><i><MailFill /></i></div><h5>购物车为空</h5><Button className='shopCar_go' onClick={() => navigate('/find')}>去逛逛</Button></div>
          }
          <div className='parts'>
            更多推荐
          </div>

          <div className='details details1'>
            {
              tabReducer.changeSet && <Suggest getShopCar={getShopCar}></Suggest>
            }
          </div>

        </div>
      }
    </>
  )
}




